package web.language.helper

class LearnController {

    def start() {
        List<Integer> itemIds = new ArrayList<Integer>()
        List<Dictionary> dics = Dictionary.findAll()
        for (Dictionary dic in dics) {
            if (dic.work) {
                itemIds.addAll(DictionaryController.getForLearn(dic, session.user))
            }
        }
        if (itemIds.size() == 0 ) {
            flash.message = 'There are no entity for learning!'
            redirect action: 'dicList'
        }
        session.setAttribute("learningEntries", itemIds)

        session.putValue("position", 0)
        redirect  action: "showEntry"
    }

    def showEntry() {
        List<Integer> items = (List<Integer>) session.getAttribute("learningEntries")
        Boolean direction = session.getValue("direction").toBoolean()
        Integer entryId = items.get(session.getValue("position").toInteger()).toInteger()
        Entry entry = Entry.findById(entryId)
        [phrase: (direction) ? entry.phrase : entry.translate, variants: fillVariants(entry, direction)]
    }

    Map<Integer, String> fillVariants(Entry entry, Boolean direction) {
        List<Integer> itemIds = session.getAttribute("learningEntries")
        Map<Integer, String> variants = new HashMap<Integer, String>()
        Integer rightIdx = (Math.random() * 5).toInteger()
        Entry fillEntry
        for (index in 0..4) {
            if (index == rightIdx) {
                fillEntry = entry
            } else {
                Integer idx = (Math.random() * itemIds.size()).toInteger()
                fillEntry = Entry.findById(itemIds.get(idx))
            }

            variants.put(fillEntry.id, (direction) ? fillEntry.translate : fillEntry.phrase)
        }

        session.putValue("answer", entry.id)
        variants
    }

    def replay() {
        def answer = session.getValue("answer")
        def position = session.getValue("position").toInteger()
        Entry entry = Entry.findById(params.id)

        Statistic stat = entry.statistic.find {stat -> stat.user == session.user}

        if (stat == null) {
            stat = new Statistic(user: session.user)
            stat.save()
            entry.addToStatistic(stat)
        }

        if (answer.equals(params.id)) {
            session.putValue("position", ++position)
            stat.right++
        } else {
            stat.wrong++
        }

        stat.save()
        redirect action: "showEntry"
    }

    def dicList() {
        redirect controller: "dictionary", action: "list"
    }
}
